<?php

// +----------------------------------------------------------------------
// | FaShang [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.zhixueyuan.net All rights reserved.
// +----------------------------------------------------------------------
// | Author: yike <shixiang.jin@zwtchina.com> <http://www.zhixueyuan.net>
// +----------------------------------------------------------------------

namespace app\api\controller;

use think\Cache;
use think\Config;
use think\Db;
use think\Request;

class Weixin extends Common
{
    private $appid = '';
    private $secret = '';
    private $wechatAuth = '';

    public function __construct()
    {

        $this->appid = Config::get('weixin.appId'); 
        $this->secret = Config::get('weixin.appSecret');
        $this->wechatAuth = new \WechatAuth($this->appid, $this->secret);
        if (empty($this->appid)) {
            return ajax_return_error('appId配置有误',2);
        }
        parent::__construct();
    }


    /**
     * 微信jssdk授权
     */
    public function jssdkInfo()
    {
        $url = input('url');
	
        if (empty($url)) {
            return ajax_return_error( 'url参数为空');
        }
        $url = str_replace('@@','/',$url);
        $url = base64_decode($url);

        $ticket = json_decode(Cache::get('jsapiTicket'), true);
        if (empty($ticket)) {

            $wxdata = json_decode(Cache::get('WXAccessToken'), true);
            if (empty($wxdata)) {
                $wxdata = $this->wechatAuth->getAccessToken();
                Cache::set('WXAccessToken', json_encode($wxdata), $wxdata['expires_in']);
            }
            $ticket = $this->wechatAuth->getJsapiTicket($wxdata['access_token']);
            Cache::set('jsapiTicket', json_encode($ticket), $ticket['expires_in']);
        }

        $noncestr = 'tpQueuejs' . mt_rand(10000, 999999);
        $timestamp = NOW_TIME;
        $str = 'jsapi_ticket=' . $ticket['ticket'] . '&noncestr=' . $noncestr . '&timestamp=' . $timestamp . '&url=' . $url;
        $signature = sha1($str);

        $content = array(
            'appId' => $this->appid,
            'nonceStr' => $noncestr,
            'signature' => $signature,
            'timestamp' => $timestamp,
            'url' => $url,
            'str' => $str,
 //           'ticket' => $ticket,
        );
        return ajax_return($content);
    }


    /**
     * 微信网页授权登录
     */
    public function wechatLogin()
    {
        $refererUrl = input('url');
        session(null);
        file_put_contents('uploads/wxoauth.txt', date('Y-m-d H:i:s') . '$refererUrl ' . $refererUrl . PHP_EOL, FILE_APPEND);

        $redirect = Config::get('DOMAIN_NAME') . url('api/Weixin/wechatCallback', ['httpReferer'=> $refererUrl, 'parent_id' => input('request.parent_id'), 'sessionid' => session_id()]);
        $url = $this->wechatAuth->getRequestCodeURL($redirect, 1);
        $this->redirect($url);
        file_put_contents('uploads/wxoauth.txt', date('Y-m-d H:i:s') . $url . PHP_EOL, FILE_APPEND);
        return ajax_return($url);
    }

    /**
     * 微信登陆回调地址
     * 如果需要手机微信注册 请用这个方法
     * 参考文档：http://mp.weixin.qq.com/wiki/9/01f711493b5a02f24b04365ac5d8fd95.html
     * @return [type] [description]
     */
    public function wechatCallback()
    {

        $code = input('request.code');
        $parent_id = input('request.parent_id',0); //二维码推荐时带上推荐人id
        $httpReferer = input('httpReferer');
        $httpReferer = str_replace('@@','/',$httpReferer);
        $httpReferer = base64_decode($httpReferer);
        if (empty($code)) {
            return ajax_return_error('code参数为空');
        }
        file_put_contents('uploads/wxoauth.txt', date('Y-m-d H:i:s') . ' $httpReferer ' . $httpReferer . PHP_EOL, FILE_APPEND);
        $wxdata = $this->wechatAuth->getAccessToken('code', $code);

        //获取AUTH用户资料
        $userInfo = $this->wechatAuth->getUserinfo($wxdata);
        file_put_contents('uploads/wxoauth.txt', date('Y-m-d H:i:s') . json_encode($userInfo) . $parent_id . PHP_EOL, FILE_APPEND);
        if (empty($userInfo['openid'])) {
            return ajax_return_error('获取用户信息失败');
        }
        $userInfo['unionid'] = isset($userInfo['unionid']) ? $userInfo['unionid']: '';
        $this->wxLogin($userInfo['nickname'], $userInfo['openid'], $userInfo['unionid'], $userInfo['headimgurl'], $parent_id);
        if ($this->result['error'] > 0) {
            return ajax_return_error($this->result['msg']);
        } else {

            $httpReferer = empty($httpReferer)? Config::get('DOMAIN_NAME').'/' : $httpReferer;
            $url = $httpReferer.'?uuid/@'.$this->result['uuid'];
            file_put_contents('uploads/wxoauth.txt', date('Y-m-d H:i:s') . 'url ' . $url .' AAAA '.$httpReferer. PHP_EOL, FILE_APPEND);
            $this->redirect($url);
        }
    }

    /**
     * 微信登录
     * @param type $nickname
     * @param type $openid
     * @param type $unionid
     * @param type $head_portrait
     */
    private function wxLogin($nickname = '', $openid = '', $unionid = '', $head_portrait = '', $parent_id = 0)
    {

        $unionid = empty($unionid) ? $openid : $unionid;
        /* 判读是否存在unionid的用户 */
        $unioninfo = model('member')->where(['unionid' => $unionid])->find();

        if (empty($unioninfo)) {file_put_contents('uploads/wxoauth.txt', date('Y-m-d H:i:s') . ' 1 '  . PHP_EOL, FILE_APPEND);
            //不存在为 openid的用户,注册unionid用户
            /* 调用注册接口注册用户 */
            $Member = model('member');
//                $password = 'mobiletv2016';    //默认赋值密码
            /* 在当前应用中注册用户 */
            $Member->data([
                'uuid' => session_id(),
                'openid' => $openid,
                'unionid' => $unionid,  //微信登录的用户名
                'nickname' => $nickname,
                'parent_id' => $parent_id,
                'head_portrait' => $head_portrait,
                'reg_ip'=> Request::instance()->ip(1),
                'status' => 1,
            ]);
            if (!$Member->save()) {
                file_put_contents('uploads/wxoauth.txt', date('Y-m-d H:i:s') . ' 2 '.$Member->getError()  . PHP_EOL, FILE_APPEND);
                $this->result['error'] = 101;
                $this->result['msg'] = '注册失败';
                $this->result['msg1'] = $Member->getError();
                return;
            }

            /* 登录用户 */
            $Member->autoLogin($Member);
            $this->result['uuid'] = $Member->uuid;
            $this->result['uid'] = $Member->getLastInsID();
            $this->result['error'] = 0;
            $this->result['msg'] = '登陆成功';
            return;
        }

        /* 登录流程只存在使用unionid登录 */
        $memberInfo =  Db::name('member')->field('uid, status')->where(array('unionid' => $unionid))->find();
        file_put_contents('uploads/wxoauth.txt', date('Y-m-d H:i:s') . json_encode($memberInfo)  . PHP_EOL, FILE_APPEND);
        if (!empty($memberInfo['uid'])) {
            /* 登录用户 */
            $Member =   model('member');
            $uuid = $Member->login($memberInfo['uid']);
            if ($uuid) { //登录用户

                $this->result['error'] = 0;
                $this->result['msg'] = '登录成功';
                $this->result['uuid'] = $uuid;
                $this->result['uid'] = $memberInfo['uid'];
                return;
            } else {
                $this->result['error'] = 101;
                $this->result['msg'] = '用户未激活或已禁用！';
                return;
            }
        } else {

            $this->result['error'] = 104;
            $this->result['msg'] = '用户不存在！';
            return;
        }
    }


}
